package com.ssm.basis.web.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpMethod;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
public abstract class WebResourceUtil {
    static RestTemplate restTemplate;

    public static void fileDownload(String url, String directory, String filename) {
        try {
            Path outputPath = Paths.get(directory);
            if (!Files.exists(outputPath)) Files.createDirectories(outputPath);
            if (!Files.isWritable(outputPath)) throw new IOException("path is not writable: " + directory);

            restTemplate.execute(url, HttpMethod.GET, request -> {
                // request.getHeaders().set(HttpHeaders.ACCEPT, MediaType.APPLICATION_OCTET_STREAM_VALUE);
                // request.getHeaders().setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));
            }, response -> {
                if (response.getStatusCode().isError())
                    throw new IOException("response code: " + response.getStatusCode());

                Path targetPath;
                if (filename == null) {
                    String fn = response.getHeaders().getContentDisposition().getFilename();
                    if (!StringUtils.hasText(fn))
                        fn = "download_" + System.currentTimeMillis() + "_" + StringUtils.getFilename(url);
                    targetPath = outputPath.resolve(fn);
                } else targetPath = outputPath.resolve(filename);

                try (InputStream inputStream = response.getBody();
                     OutputStream outputStream = Files.newOutputStream(targetPath)) {
                    StreamUtils.copy(inputStream, outputStream); // FileCopyUtils
                }
                return null;
            });
        } catch (IOException e) {
            log.error(url, e);
        }
    }

    public static byte[] fileDownload(String url) {
        return restTemplate.getForObject(url, byte[].class);
    }

    @Autowired
    public void setRestTemplate(RestTemplateBuilder restTemplateBuilder) {
        WebResourceUtil.restTemplate = restTemplateBuilder.build();
    }
}